import axios from 'axios';
import { NETWORK_EXPIRES_TIME } from './constants';
// import { getParamFromSearch } from './utils';
// import KNB from '@dp/knb';
import Store from '../store';
axios.defaults.timeout = NETWORK_EXPIRES_TIME;
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
// axios.defaults.headers.common['swimlane'] = '3157-bkvfj';
axios.interceptors.response.use((response) => {
  if (response.data.code !== 200) {
    // 网络请求成功，但接口数据异常时上报

    // TODO: 请求失败界面提示
    // KNB.toast({
    //     content: response.data.message
    // });
    window.Owl.addError({
      name: 'request error',
      msg: response.data.message
    }, {
      combo: false,
      level: window.Owl.errorModel.LEVEL['ERROR'],
      category: window.Owl.errorModel.CATEGORY.SCRIPT
    });
  }
  return response.data;
}, (error) => {
  if (error.message.match('timeout')) {
    error.message = '网路超时，请检查您网络状态';
  }
  return Promise.reject(error);
});

const request = function handleAjax () {
  // console.log(Store.state);
  // let userId = getParamFromSearch('userid');
  // let token = getParamFromSearch('token');
  let userId = Store.state.userid;
  let token = Store.state.token;
  let options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  let data = Object.assign({
    userId: userId,
    token: token,
    t: new Date().getTime()
  }, options.data || {});
  let opt = {
    url: options.url || '',
    data: data || 't=' + new Date().getTime(),
    type: options.type || 'get',
    dataType: options.dataType || 'json',
    cache: options.cache || false,
    async: options.async || true,
    context: options.context || document.body,
    beforeSend: options.beforeSend || undefined
  };
  if (opt.type === 'get') {
    return axios.get(opt.url, {
      params: opt.data
    });
  } else if (opt.type === 'post') {
    opt.url += '?userId=' + userId + '&token=' + token;
    let data = Object.assign({}, {
      userId
    }, opt.data);
    return axios.post(opt.url, data);
  }
};
export default request;
